package pro.softzhang.algo.lc200;

import pro.softzhang.algo.common.TreeNode;

/**
 * 236. 二叉树的最近公共祖先
 * https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/description/
 */
public class LC236_LowestCommonAncestorOfABinaryTree {
    public static void main(String[] args) {

    }

    /**
     * 分类讨论
     */
    static
    class Solution {
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            if(root == null || root == p || root == q) return root;
            TreeNode left = lowestCommonAncestor(root.left, p, q);
            TreeNode right = lowestCommonAncestor(root.right, p, q);
            return left != null && right != null ?
                    root :
                    (left != null ? left : right);
        }
    }
}
